# plugs/mailexceptions.py
#
#

""" mail exceptions in backlog """

__status__ = "seen"

## gozerbot imports

from gozerbot.commands import cmnds
from gozerbot.examples import examples
from gozerbot.utils.exception import exceptionlist
from gozerbot.plughelp import plughelp
from gozerbot.tests import tests

## basic imports

import smtplib

## plughelp

plughelp.add('mailexceptions', 'mail list of occured exceptions to bthate@gmail.com')

def handle_mailexceptions(bot, ievent):
    """ mailexceptions [<email>] .. mail exceptions in log """
    if not len(exceptionlist): ievent.reply("no exceptions available") ; return   
    try: mailto = ievent.args[0]
    except IndexError: mailto = 'bthate@gmail.com'
    try: mailserver = mailto.split('@')[1]
    except IndexError: ievent.reply("can't determine mailserver from %s" % mailto) ; return
    fromaddr = 'gozerbot@localhost'
    msg = ("From: %s\r\nTo: %s\r\n\r\n" % (fromaddr, mailto))
    for i in exceptionlist: msg += "+++ %s\r\n" % i 
    server = smtplib.SMTP(mailserver)
    server.sendmail(fromaddr, mailto, msg)
    ievent.reply("%s exceptions send to %s" % (len(exceptionlist), mailto))

cmnds.add('mailexceptions', handle_mailexceptions, 'OPER')
examples.add('mailexceptions' , 'mailexceptions [<email>] .. mail exceptions log to bthate@gmail.com or to provided email', '1) mailexceptions 2) \
mailexception bthate@gmail.com')
tests.add('mailexceptions bthate@gmail.com', 'exceptions send to bthate@gmail.com')

#### BHJTW 23-01-2012
